package com.fgs.common.pictureSelector;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fgs.common.R;
import com.fgs.common.interf.OnLocationCheckListener;
import com.fgs.common.utils.LogUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnItemClickListener;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.SdkVersionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fgs
 * @date 2019/9/12
 **/
public class SelectPicture {

    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    public static final int RATIO_DEFAULT = 0;
    public static final int RATIO_16_3 = 1;
    public static final int RATIO_1_1 = 2;

    private int maxSelectNum = 6;
    private int selectType = PictureConfig.SINGLE;
    private final int chooseMode = PictureMimeType.ofImage();
    private OnSelectResultCallback selectResultCallback;
    private OnLocationCheckListener onLocationCheckListener;
    private boolean isCrop = false;
    private boolean isCarma = true;
    private int ratioX = 0;
    private int ratioY = 0;

    public SelectPicture() {

    }

    public void setAspectRatio(int ratioType) {
        if (ratioType == RATIO_DEFAULT) {
            ratioX = 0;
            ratioY = 0;
        } else if (ratioType == RATIO_16_3) {
            ratioX = 16;
            ratioY = 3;
        } else if (ratioType == RATIO_1_1) {
            ratioX = 1;
            ratioY = 1;
        }

    }

    public void setIsCarma(boolean isCarma) {
        this.isCarma = isCarma;
    }

    public void setCrop(boolean crop) {
        isCrop = crop;
    }

    public void setMaxSelectNum(int maxSelectNum) {
        this.maxSelectNum = maxSelectNum;
    }

    public void setAdapterData(List<LocalMedia> selectList) {
        if (selectList == null) return;
        this.selectList = selectList;
        adapter.setList(selectList);
        adapter.notifyDataSetChanged();
    }

    public void setOnLocationCheckListener(OnLocationCheckListener onLocationCheckListener) {
        this.onLocationCheckListener = onLocationCheckListener;
    }

    public void selectMultiPicture(Activity activity, OnSelectResultCallback onSelectResultCallback, RecyclerView recyclerView) {
        if (recyclerView == null) return;
        // 进入相册 以下是例子：不需要的api可以不写
        multiSelectConfig(activity, onSelectResultCallback, recyclerView, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                if (onLocationCheckListener != null) {
                    if (onLocationCheckListener.onLocationCheck()) {
                        setPictureSelectConfig(PictureSelector.create(activity), selectResultCallback);
                    }
                } else {
                    setPictureSelectConfig(PictureSelector.create(activity), selectResultCallback);
                }

            }
        });

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getMimeType();
                    int mediaType = PictureMimeType.getMimeType(pictureType);
                    switch (mediaType) {
                        case PictureConfig.TYPE_IMAGE:
                            // 预览图片 可自定长按保存路径
                            PictureSelector.create(activity)
                                    .themeStyle(R.style.picture_default_style) // xml设置主题
                                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                    .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                    .openExternalPreview(position, selectList);
                            break;
                    }
                }
            }
        });
    }

    public void selectMultiPicture(Fragment fragment, OnSelectResultCallback onSelectResultCallback, RecyclerView recyclerView) {
        // 进入相册 以下是例子：不需要的api可以不写
        multiSelectConfig(fragment.getContext(), onSelectResultCallback, recyclerView, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                setPictureSelectConfig(PictureSelector.create(fragment), selectResultCallback);
            }
        });

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getMimeType();
                    int mediaType = PictureMimeType.getMimeType(pictureType);
                    switch (mediaType) {
                        case PictureConfig.TYPE_IMAGE:
                            // 预览图片 可自定长按保存路径
                            PictureSelector.create(fragment)
                                    .themeStyle(R.style.picture_default_style) // xml设置主题
                                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                    .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                    .openExternalPreview(position, selectList);
                            break;
                    }
                }
            }
        });
    }


    public void selectSinglePicture(Activity activity, OnSelectResultCallback onSelectResultCallback) {
        // 进入相册 以下是例子：不需要的api可以不写
        singleSelectConfig(PictureSelector.create(activity), onSelectResultCallback);
    }

    public void selectSinglePicture(Fragment fragment, OnSelectResultCallback onSelectResultCallback) {
        // 进入相册 以下是例子：不需要的api可以不写
        singleSelectConfig(PictureSelector.create(fragment), onSelectResultCallback);
    }

    public interface OnSelectResultCallback {
        void selectResultCallback(List<LocalMedia> selectList);

        void selectResultPath(String path);

        void deletePictureCallback(List<LocalMedia> selectList, int position);
    }

    private void multiSelectConfig(Context context, OnSelectResultCallback onSelectResultCallback, RecyclerView recyclerView, GridImageAdapter.onAddPicClickListener onAddPicClickListener) {
        selectType = PictureConfig.MULTIPLE;
        this.selectResultCallback = onSelectResultCallback;
        FullyGridLayoutManager manager = new FullyGridLayoutManager(context, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(context, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        recyclerView.setAdapter(adapter);

        adapter.setOnDeletePictureClickListener(new GridImageAdapter.OnDeletePictureClickListener() {
            @Override
            public void onDeletePictureClick(List<LocalMedia> list, int position) {
                onSelectResultCallback.deletePictureCallback(list, position);
            }
        });

    }

    private void singleSelectConfig(PictureSelector pictureSelector, OnSelectResultCallback onSelectResultCallback) {
        maxSelectNum = 1;
        selectType = PictureConfig.SINGLE;
        setPictureSelectConfig(pictureSelector, onSelectResultCallback);
    }


    private void setPictureSelectConfig(PictureSelector pictureSelector, OnSelectResultCallback onSelectResultCallback) {
        pictureSelector.openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                .maxSelectNum(maxSelectNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
//                .loadCacheResourcesCallback(GlideCacheEngine.createCacheEngine())// 获取图片资源缓存，主要是解决华为10部分机型在拷贝文件过多时会出现卡的问题，这里可以判断只在会出现一直转圈问题机型上使用
                .selectionMode(selectType)// 多选 or 单选
                .isSingleDirectReturn(false)
                .previewImage(true)// 是否可预览图片
                .isCamera(isCarma)// 是否显示拍照按钮
                .enableCrop(isCrop)// 是否裁剪
                .compress(true)// 是否压缩
                .compressQuality(100)// 图片压缩后输出质量 0~ 100
                .synOrAsy(false)//同步true或异步false 压缩 默认同步
                .withAspectRatio(ratioX, ratioY)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .isDragFrame(true)// 是否可拖动裁剪框(固定)
                .cutOutQuality(100)// 裁剪输出质量 默认100
                .minimumCompressSize(100)// 小于200kb的图片不压缩
                .scaleEnabled(true)// 裁剪是否可放大缩小图片
                .selectionMedia(selectList)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        for (LocalMedia media : result) {
//                            LogUtil.print("是否压缩:" + media.isCompressed());
//                            LogUtil.print("压缩:" + media.getCompressPath());
//                            LogUtil.print("原图:" + media.getPath());
//                            LogUtil.print("是否裁剪:" + media.isCut());
//                            LogUtil.print("裁剪:" + media.getCutPath());
//                            LogUtil.print("是否开启原图:" + media.isOriginal());
//                            LogUtil.print("原图路径:" + media.getOriginalPath());
//                            LogUtil.print("Android Q 特有Path:" + media.getAndroidQToPath());
//                            LogUtil.print("Android Q RealPath:" + media.getRealPath());
                            LogUtil.print("Size: " + media.getSize() / 1024 + "k");

                        }

                        LocalMedia media = result.get(0);
                        if (media == null
                                || TextUtils.isEmpty(media.getPath())) {
                            return;
                        }
                        String path;
                        if (media.isCut() && !media.isCompressed()) {
                            // 裁剪过
                            path = media.getCutPath();
                        } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准

                            path = media.getCompressPath();
                        } else {
                            // 原图
                            path = media.getPath();
                        }

                        if (null != onSelectResultCallback) {
                            if (result != null && result.size() > 0) {

                                onSelectResultCallback.selectResultCallback(result);
                                if (null != adapter) {
                                    setAdapterData(result);
                                }

                            }
                            onSelectResultCallback.selectResultPath(path);
                        }


                    }

                    @Override
                    public void onCancel() {
                        LogUtil.print("PictureSelector Cancel");
                    }
                });
    }

    public void previewImage(Activity activity, List<LocalMedia> list, int position) {
        PictureSelector.create(activity)
                .themeStyle(R.style.picture_default_style)
                .isNotPreviewDownload(true)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .openExternalPreview(position, list);
    }


//    public String getMultiSelectPictureId() {
//        int size = selectList.size();
//        StringBuffer stringBuffer = new StringBuffer();
//        if (size > 0) {
//            for (int i = 0; i < size; i++) {
//                stringBuffer.append(selectList.get(i));
//                stringBuffer.append(",");
//            }
//            String string = stringBuffer.toString();
//
//            return string.substring(0, string.length() - 1);
//        } else {
//            return "";
//        }
//
//    }

    public void removePicture(int position) {
        if (adapter != null && adapter.getData() != null) {
            int size = adapter.getData().size();
            if (position < size) {
                adapter.getData().remove(position);
                adapter.notifyDataSetChanged();
            }
        }

    }

    public void removePicture(LocalMedia localMedia) {
        if (adapter != null && adapter.getData() != null) {
            adapter.getData().remove(localMedia);
            adapter.notifyDataSetChanged();
        }

    }

    public void clearPicture() {
        if (adapter != null && adapter.getData() != null) {
            adapter.getData().clear();
            adapter.notifyDataSetChanged();
        }
    }



    //===============================================================================
    //直接拍照
    public void photographPicture(Activity activity, OnSelectResultCallback onSelectResultCallback, RecyclerView recyclerView) {
        if (recyclerView == null) return;
        // 进入相册 以下是例子：不需要的api可以不写
        multiSelectConfig(activity, onSelectResultCallback, recyclerView, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                if (onLocationCheckListener != null) {
                    if (onLocationCheckListener.onLocationCheck()) {
                        setPicturePhotograph(PictureSelector.create(activity), selectResultCallback);
                    }
                } else {
                    setPicturePhotograph(PictureSelector.create(activity), selectResultCallback);
                }

            }
        });

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getMimeType();
                    int mediaType = PictureMimeType.getMimeType(pictureType);
                    switch (mediaType) {
                        case PictureConfig.TYPE_IMAGE:
                            // 预览图片 可自定长按保存路径
                            PictureSelector.create(activity)
                                    .themeStyle(R.style.picture_default_style) // xml设置主题
                                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                    .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                    .openExternalPreview(position, selectList);
                            break;
                    }
                }
            }
        });
    }

    private void setPicturePhotograph(PictureSelector pictureSelector, OnSelectResultCallback onSelectResultCallback) {
        pictureSelector.openCamera(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                .maxSelectNum(maxSelectNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
//                .loadCacheResourcesCallback(GlideCacheEngine.createCacheEngine())// 获取图片资源缓存，主要是解决华为10部分机型在拷贝文件过多时会出现卡的问题，这里可以判断只在会出现一直转圈问题机型上使用
                .selectionMode(selectType)// 多选 or 单选
                .isSingleDirectReturn(false)
                .previewImage(true)// 是否可预览图片
                .isCamera(isCarma)// 是否显示拍照按钮
                .enableCrop(isCrop)// 是否裁剪
                .compress(true)// 是否压缩
                .compressQuality(100)// 图片压缩后输出质量 0~ 100
                .synOrAsy(false)//同步true或异步false 压缩 默认同步
                .withAspectRatio(ratioX, ratioY)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .isDragFrame(true)// 是否可拖动裁剪框(固定)
                .cutOutQuality(100)// 裁剪输出质量 默认100
                .minimumCompressSize(100)// 小于200kb的图片不压缩
                .scaleEnabled(true)// 裁剪是否可放大缩小图片
                .selectionMedia(selectList)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        for (LocalMedia media : result) {
//                            LogUtil.print("是否压缩:" + media.isCompressed());
//                            LogUtil.print("压缩:" + media.getCompressPath());
//                            LogUtil.print("原图:" + media.getPath());
//                            LogUtil.print("是否裁剪:" + media.isCut());
//                            LogUtil.print("裁剪:" + media.getCutPath());
//                            LogUtil.print("是否开启原图:" + media.isOriginal());
//                            LogUtil.print("原图路径:" + media.getOriginalPath());
//                            LogUtil.print("Android Q 特有Path:" + media.getAndroidQToPath());
//                            LogUtil.print("Android Q RealPath:" + media.getRealPath());
                            LogUtil.print("Size: " + media.getSize() / 1024 + "k");

                        }

                        LocalMedia media = result.get(0);
                        if (media == null
                                || TextUtils.isEmpty(media.getPath())) {
                            return;
                        }
                        String path;
                        if (media.isCut() && !media.isCompressed()) {
                            // 裁剪过
                            path = media.getCutPath();
                        } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准

                            path = media.getCompressPath();
                        } else {
                            // 原图
                            path = media.getPath();
                        }

                        if (null != onSelectResultCallback) {
                            if (result != null && result.size() > 0) {

                                onSelectResultCallback.selectResultCallback(result);
                                if (null != adapter) {
                                    setAdapterData(result);
                                }

                            }
                            onSelectResultCallback.selectResultPath(path);
                        }


                    }

                    @Override
                    public void onCancel() {
                        LogUtil.print("PictureSelector Cancel");
                    }
                });
    }

}
